package business_opportunity

import (
	"context"
	"encoding/json"
	"errors"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	pb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	businessOpportunityProject "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/business_opportunity/project"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/job_center"
	"git.myscrm.cn/golang/stark/v4"
)

type projectServer struct {
	businessProjectService businessOpportunityProject.ProjectServiceIface
	jobService             job_center.JobCenterServiceIface
}

func NewProjectServer(
	businessProjectService businessOpportunityProject.ProjectServiceIface,
	jobService job_center.JobCenterServiceIface,
) pb.ProjectServiceServer {
	return &projectServer{
		businessProjectService: businessProjectService,
		jobService:             jobService,
	}
}

// SearchProject 搜索项目
func (s *projectServer) SearchProject(ctx context.Context, request *pb.SearchProjectRequest) (*pb.SearchProjectResponse, error) {
	resp, err := s.businessProjectService.SearchProject(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc SearchProject request:%+v, err:%s", request, err)
		return nil, err
	}
	return resp, nil
}

// FuzzySearchProject 模糊搜索项目
func (s *projectServer) FuzzySearchProject(ctx context.Context, request *pb.FuzzySearchProjectRequest) (*pb.FuzzySearchProjectResponse, error) {
	resp, err := s.businessProjectService.FuzzySearchProject(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc FuzzySearchProject request:%+v, err:%s", request, err)
		return nil, err
	}
	return resp, nil
}

// ProjectDetail 项目详情
func (s *projectServer) ProjectDetail(ctx context.Context, request *pb.ProjectDetailRequest) (*pb.ProjectDetailResponse, error) {
	var errMsg string
	if request.GetId() == "" {
		errMsg = "id参数缺失"
	}
	if errMsg != "" {
		return nil, errors.New(errMsg)
	}
	resp, err := s.businessProjectService.ProjectDetail(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ProjectDetail request:%+v, err:%s", request, err)
		return nil, err
	}
	return resp, nil
}

// ProjectDetailLand 项目详情，拿地列表
func (s *projectServer) ProjectDetailLand(ctx context.Context, request *pb.ProjectDetailLandRequest) (*pb.ProjectDetailLandResponse, error) {
	resp, err := s.businessProjectService.ProjectDetailLand(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ProjectDetailLand request:%+v, err:%s", request, err)
		return nil, err
	}
	return resp, nil
}

// ProjectDetailBuild 项目详情，在建列表
func (s *projectServer) ProjectDetailBuild(ctx context.Context, request *pb.ProjectDetailBuildRequest) (*pb.ProjectDetailBuildResponse, error) {
	resp, err := s.businessProjectService.ProjectDetailBuild(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ProjectDetailBuild request:%+v, err:%s", request, err)
		return nil, err
	}
	return resp, nil
}

// ProjectDetailSale 项目详情，开盘列表
func (s *projectServer) ProjectDetailSale(ctx context.Context, request *pb.ProjectDetailSaleRequest) (*pb.ProjectDetailSaleResponse, error) {
	resp, err := s.businessProjectService.ProjectDetailSale(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ProjectDetailSale request:%+v, err:%s", request, err)
		return nil, err
	}
	return resp, nil
}

// ProjectDetailBid 项目详情，招中标列表
func (s *projectServer) ProjectDetailBid(ctx context.Context, request *pb.ProjectDetailBidRequest) (*pb.ProjectDetailBidResponse, error) {
	resp, err := s.businessProjectService.ProjectDetailBid(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ProjectDetailBid request:%+v, err:%s", request, err)
		return nil, err
	}
	return resp, nil
}

// TakenLandDetail 拿地详情
func (s *projectServer) TakenLandDetail(ctx context.Context, request *pb.TakenLandDetailRequest) (*pb.TakenLandDetailResponse, error) {
	var errMsg string
	if request.GetId() == "" {
		errMsg = "id参数缺失"
	}
	if errMsg != "" {
		return nil, errors.New(errMsg)
	}
	res, err := s.businessProjectService.TakenLandDetail(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "TakenLandDetail 获取拿地详情失败，参数:%+v, 错误信息：%s", request, err.Error())
		return nil, err
	}
	return res, nil
}

// SaleList 开盘列表
func (s *projectServer) SaleList(ctx context.Context, request *pb.SaleListRequest) (*pb.SaleListResponse, error) {
	res, err := s.businessProjectService.SaleList(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "SaleList 获取开盘列表失败，参数:%+v, 错误信息：%s", request, err.Error())
		return nil, err
	}
	return res, nil
}

// ExportSaleList 开盘列表-导出
func (s *projectServer) ExportSaleList(ctx context.Context, request *pb.ExportSaleListRequest) (*pb.ExportSaleListResponse, error) {
	listResp, err := s.businessProjectService.SaleList(ctx, &pb.SaleListRequest{
		PageSize:              1,
		Page:                  1,
		Keyword:               request.Keyword,
		CompanyArea:           request.CompanyArea,
		CompanyType:           request.CompanyType,
		IsPriceGtAvg:          request.IsPriceGtAvg,
		FitmentFeeLabel:       request.FitmentFeeLabel,
		PropertyCategoryLabel: request.PropertyCategoryLabel,
		OpeningTimeStart:      request.OpeningTimeStart,
		OpeningTimeEnd:        request.OpeningTimeEnd,
		DeliveryTimeStart:     request.DeliveryTimeStart,
		DeliveryTimeEnd:       request.DeliveryTimeEnd,
		CompanyLabel:          request.CompanyLabel,
		Area:                  request.Area,
	})

	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ExportSaleList SaleList request:%+v, err:%s", request, err.Error())
		return nil, err
	}
	if listResp.Total == 0 {
		return nil, errors.New("导出数据为空")
	}
	if listResp.Total > 10000 {
		listResp.Total = 10000
	}

	requestBytes, _ := json.Marshal(request)

	jobId, err := s.jobService.NewJob(ctx, constants.JobMethodExport, constants.JobTypeSaleExport, listResp.Total, string(requestBytes))
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ExportSaleList NewJob request:%+v, err:%s", request, err.Error())
		return nil, err
	}

	_ = s.jobService.StartJob(ctx, jobId)

	return &pb.ExportSaleListResponse{JobId: jobId, IsSucceed: true}, nil
}

// SaleDetail 开盘详情
func (s *projectServer) SaleDetail(ctx context.Context, request *pb.SaleDetailRequest) (*pb.SaleDetailResponse, error) {
	var errMsg string
	if request.GetId() == "" {
		errMsg = "id参数缺失"
	}
	if errMsg != "" {
		return nil, errors.New(errMsg)
	}
	res, err := s.businessProjectService.SaleDetail(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "SaleDetail 获取开盘详情失败，参数:%+v, 错误信息：%s", request, err.Error())
		return nil, err
	}
	return res, nil
}

// NewHouse 新房销售数据
func (s *projectServer) NewHouse(ctx context.Context, request *pb.NewHouseRequest) (*pb.NewHouseResponse, error) {
	if request.GetOrganizingCode() == "" || request.GetPresellNum() == "" {
		return &pb.NewHouseResponse{}, nil
	}
	res, err := s.businessProjectService.NewHouse(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "NewHouse 获取新房销售数据失败，参数:%+v, 错误信息：%s", request, err.Error())
		return nil, err
	}
	return res, nil
}

// GetTopProject 获取项目主体
func (s *projectServer) GetTopProject(ctx context.Context, request *pb.GetTopProjectRequest) (*pb.GetTopProjectResponse, error) {
	var errMsg string
	if request.GetId() == "" {
		errMsg = "id参数缺失"
	}
	if errMsg != "" {
		return nil, errors.New(errMsg)
	}
	res, err := s.businessProjectService.GetTopProject(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetTopProject 获取项目主体失败，参数:%+v, 错误信息：%s", request, err.Error())
		return nil, err
	}
	return res, nil
}

// GetTakeLandList 拿地列表
func (s *projectServer) GetTakeLandList(ctx context.Context, request *pb.GetTakeLandListRequest) (*pb.GetTakeLandListResponse, error) {
	resp, err := s.businessProjectService.GetTakenLand(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc GetTakeLandList request:%+v, err:%s", request, err.Error())
		return nil, err
	}
	return resp, nil
}

func (s *projectServer) ExportTakeLandList(ctx context.Context, request *pb.ExportTakeLandListRequest) (*pb.ExportTakeLandListResponse, error) {
	takeLandListResp, err := s.businessProjectService.GetTakenLand(ctx, &pb.GetTakeLandListRequest{
		OrganizingCode:    request.OrganizingCode,
		Keyword:           request.Keyword,
		AreaCode:          request.AreaCode,
		TakeLandDateStart: request.TakeLandDateStart,
		TakeLandDateEnd:   request.TakeLandDateEnd,
		LandUsage:         request.LandUsage,
		Page:              1,
		PageSize:          1,
		LandAreaMin:       request.LandAreaMin,
		LandAreaMax:       request.LandAreaMax,
		LandPriceMin:      request.LandPriceMin,
		LandPriceMax:      request.LandPriceMax,
		IsPriceGtAvg:      request.IsPriceGtAvg,
		CompanyAreaCode:   request.CompanyAreaCode,
		CompanyType:       request.CompanyType,
		CompanyLabel:      request.CompanyLabel,
	})
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ExportTakeLandList GetTakenLand request:%+v, err:%s", request, err.Error())
		return nil, err
	}
	if takeLandListResp.Total == 0 {
		return nil, errors.New("导出数据为空")
	}
	if takeLandListResp.Total > 10000 {
		takeLandListResp.Total = 10000
	}
	requestBytes, _ := json.Marshal(request)
	jobId, err := s.jobService.NewJob(ctx, constants.JobMethodExport, constants.JobTypeLandExport, takeLandListResp.Total, string(requestBytes))
	if err != nil {
		stark.Logger.Errorf(ctx, "grpc ExportTakeLandList NewJob request:%+v, err:%s", request, err.Error())
		return nil, err
	}

	_ = s.jobService.StartJob(ctx, jobId)

	return &pb.ExportTakeLandListResponse{JobId: jobId}, nil
}
